//
//  YTResetPasswordViewController.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/5/23.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTResetPasswordViewController.h"
#import "YTUserProfileServices.h"

@interface YTResetPasswordViewController ()
@property (weak, nonatomic) IBOutlet UITextField *oldPasswordText;
@property (weak, nonatomic) IBOutlet UITextField *nowPasswordText;
@property (weak, nonatomic) IBOutlet UITextField *nowPasswordAgain;
@property (weak, nonatomic) IBOutlet UIButton *resetBtn;
@property (weak, nonatomic) IBOutlet UILabel *tipsText;
@end

@implementation YTResetPasswordViewController

- (void)initialize {
    
    id (^passwordValidate)(NSString *str) = ^id(NSString *value) {
        return @(value.length >= 6);
    };
    
    RACSignal *old = [_oldPasswordText.rac_textSignal map:passwordValidate];
    RACSignal *now = [_nowPasswordText.rac_textSignal map:passwordValidate];
    RACSignal *nowAgain = [_nowPasswordAgain.rac_textSignal map:passwordValidate];
    UIColor *(^textColor)(NSNumber *redable) = ^UIColor *(NSNumber *redable) {
        return redable.boolValue ? kBlackColor : [UIColor redColor];
    };
    
    RAC(_oldPasswordText, textColor) = [old map:textColor];
    RAC(_nowPasswordAgain, textColor) = [nowAgain map:textColor];
    RAC(_nowPasswordText, textColor) = [now map:textColor];
    @weakify(self);
    RACSignal *showTips = [RACSignal combineLatest:@[old, now, _nowPasswordAgain.rac_textSignal]
                                            reduce:^id(NSNumber *old, NSNumber *now, NSString *nowAgain){
        @strongify(self);
        return @(old.boolValue && now.boolValue && ![nowAgain isEqualToString:self.nowPasswordText.text] && nowAgain.length > 1);
    }];
    
    [showTips subscribeNext:^(NSNumber *isShow) {
        @strongify(self);
        self.tipsText.hidden = !isShow.boolValue;
    }];
    
    RACSignal *enableSignal = [RACSignal combineLatest:@[old, nowAgain] reduce:^id(NSNumber *oldEnable, NSNumber *nowEnable){
        return @(oldEnable.boolValue && nowEnable.boolValue && [self.nowPasswordText.text isEqualToString:self.nowPasswordAgain.text]);
    }];
    
    RAC(_resetBtn, enabled) = enableSignal;
    
    [[enableSignal distinctUntilChanged] subscribeNext:^(NSNumber *enabled) {
        @strongify(self);
        self.resetBtn.backgroundColor = (enabled.boolValue ? kMainBlueColor : [UIColor lightGrayColor]);
    }];
}

- (IBAction)resetPasswordAction:(UIButton *)sender {
    NSMutableDictionary *dataDict = [NSMutableDictionary dictionaryWithCapacity:2];
    dataDict[@"oldPassword"] = _oldPasswordText.text;
    dataDict[@"newPassword"] = _nowPasswordText.text;
    @weakify(self);
    [[YTUserProfileServices resetPassword:dataDict] subscribeNext:^(id x) {
        @strongify(self);
        [self performSegueWithIdentifier:@"YTRelogin" sender:nil];
    }];
}

@end
